package com.xjrsoft.module.base.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.common.utils.UploadUtil;
import com.xjrsoft.core.tool.utils.BeanUtil;
import com.xjrsoft.core.tool.utils.CollectionUtil;
import com.xjrsoft.core.tool.utils.IoUtil;
import com.xjrsoft.core.tool.utils.WebUtil;
import com.xjrsoft.module.base.entity.XjrBaseAnnexesFile;
import com.xjrsoft.module.base.service.IXjrBaseAnnexesFileService;
import com.xjrsoft.module.base.vo.AnnexesFileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * 文件关联关系表 控制器
 *
 * @author jobob
 * @since 2020-12-22
 */
@Slf4j
@RestController
@RequestMapping("/annexes-files")
@Api(value = "文件关联关系表", tags = "文件关联关系表接口")
public class XjrBaseAnnexesFileController {
    @Autowired
    private IXjrBaseAnnexesFileService annexesFileService;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${xjrsoft.global-config.oss.enabled}")
    private boolean enabled;


    @GetMapping("/url/{folderId}")
    @ApiOperation(value = "根据文件夹Id获取图片地址")
    public Response<List<AnnexesFileVo>> getFileUrlByFolderId(@PathVariable String folderId) {
        List<XjrBaseAnnexesFile> annexesFileList = annexesFileService.list(Wrappers.<XjrBaseAnnexesFile>query().lambda().eq(XjrBaseAnnexesFile::getFolderId, folderId));
        List<AnnexesFileVo> annexesFileVoList = BeanUtil.copyList(annexesFileList, AnnexesFileVo.class);
        if (CollectionUtil.isNotEmpty(annexesFileList)) {
            String getFileApiUrlPrefix = "/annexes-files/";
            for (AnnexesFileVo annexesFileVo : annexesFileVoList) {
                annexesFileVo.setUrl(getFileApiUrlPrefix + annexesFileVo.getId());
            }
        }
        return Response.ok(annexesFileVoList);
    }

    @GetMapping("/{fileId}")
    @ApiOperation(value = "根据文件Id获取图片地址")
    public void getFileById(@PathVariable String fileId) throws IOException {
        XjrBaseAnnexesFile annexesFile = annexesFileService.getById(fileId);
        HttpServletResponse response = WebUtil.getResponse();
        response.setHeader("Content-Disposition", "inline;fileName=\"" + new String((annexesFile.getFileName()).getBytes("utf-8"), "ISO8859-1") + "\"");
       if(annexesFile!=null){
           response.setContentLengthLong(Long.valueOf(annexesFile.getFileSize()));
       }
        File file = null;
        if (annexesFile != null) {
            String filePath = annexesFile.getFilePath();
            String projectPath = IoUtil.getProjectPath();
            file = FileUtil.file(projectPath + filePath);
            if (file.exists()) {
                FileInputStream inputStream = new FileInputStream(file);
                IoUtil.copy(inputStream, response.getOutputStream());
            } else {
                IoUtil.copy(UploadUtil.download(filePath), response.getOutputStream());
            }
        }
    }

    @GetMapping("/download")
    @ApiOperation(value = "返回文件流下载")
    public ResponseEntity<byte[]> getFileDownLoadById(@RequestParam("filedId") String fileId) throws IOException {
        XjrBaseAnnexesFile annexesFile = annexesFileService.getById(fileId);
        File file = null;
        if (annexesFile != null) {
            String filePath = annexesFile.getFilePath();
            file = new File(filePath);
            if (!file.exists()) {
                String projectPath = IoUtil.getProjectPath();
                file = FileUtil.file(projectPath + filePath);
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", annexesFile.getFileName());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        assert file != null;
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据文件Id删除图片")
    public Response deleteFile(@PathVariable String id) {
        return Response.status(annexesFileService.removeById(id));
    }

    @DeleteMapping("/multi/{folderId}")
    @ApiOperation(value = "根据文件夹删除")
    public Response deleteFolderFiles(@PathVariable String folderId) {
        Wrapper<XjrBaseAnnexesFile> deleteWrapper = Wrappers.<XjrBaseAnnexesFile>query().lambda().eq(XjrBaseAnnexesFile::getFolderId, folderId);
        return Response.status(annexesFileService.remove(deleteWrapper));
    }
}
